package com.dc.designPattern._5_adapter._4_demo_mvc;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * Description: 适配器模式Demo_SpringMvc_调度业务类
 * @author: gdc
 * @date: 2021/3/11
 * @version 1.0
 */
public class DispatchServlet {

    /**
     * 存放适配器列表，组合方式
     */
    private static List<HandlerAdapter> handlerAdapters = Lists.newArrayList();
    static {
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleAdapter());
        handlerAdapters.add(new AnnotationAdapter());
    }


    public void doDispatch(){
        // step 1 此处模拟SpringMVC从request取handler的对象，适配器可以获取到希望的Controller
        Controller controller = new HttpController();
        //Controller controller = new AnnotationController();
        //Controller controller = new SimpleController();

        // step 2 获取对应适配器
        HandlerAdapter adapter = getHandlerAdapter(controller);

        // step 3通过适配器执行对应的controller对应方法
        adapter.handle(controller);

    }

    /**
     * 遍历：根据得到的controller(handler), 返回对应适配器
     * @param controller                    传入 Controller
     * @return                              对应 的 适配器
     */
    private HandlerAdapter getHandlerAdapter(Controller controller) {
        for (HandlerAdapter adapter : handlerAdapters) {
            if (adapter.supports(controller)) {
                return adapter;
            }
        }
        return null;
    }

    public static void main(String[] args){
        new DispatchServlet().doDispatch();
    }

}
